#pragma once
#include<assert.h>


namespace wjc
{
	template <class T>

	struct ListNode
	{
		ListNode<T>* _next;
		ListNode<T>* _prev;
		T _data;

		ListNode(const T& e = T())
			:_next(nullptr)
			, _prev(nullptr)
			, _data(e)
		{

		}
	};

	template<class T>
	struct _list_iterator
	{
		typedef ListNode<T> Node;
		typedef _list_iterator<T> self;
		Node* _node;

		_list_iterator(Node* x)
			:_node(x)
		{
		}

		self& operator ++()
		{
			_node = _node->_next;
			return *this;
		}

		self operator++(int)
		{
			self tmp = self(*this);
			_node = _node->_next;
			return tmp;
		}

		self& operator --()
		{
			_node = _node->_prev;
			return *this;
		}

		self operator--(int)
		{
			self tmp = self(*this);
			_node = _node->_prev;
			return tmp;
		}

		T& operator *()
		{
			return _node->_data;
		}

		bool operator !=(const self& s)
		{
			return _node != s._node;
		}
		bool operator ==(const self& s)
		{
			return _node == s._node;
		}

	};


	template<class T>
	class list
	{
		typedef ListNode<T> Node;
	public:
		typedef _list_iterator<T> iterator;
		
		list()
		{
			empty_init();
		}

		/*list(list<T>& a)
		{
			empty_init();

			for (const auto& e : a)
			{
				push_back(e);
			}
		}*/
		iterator begin()
		{
			return _head->_next;
		}

		iterator end()
		{
			return _head;
		}

		void empty_init()
		{
			_head = new Node;
			_head->_next = _head;
			_head->_prev = _head;
		}


		void swap(list<T> &a)
		{
			std::swap(_head, a._head);
		}
		list<T>& operator=(list<T>&a)
		{
			swap(a);
			return *this;
		}

		void clear()
		{
			iterator it = begin();
			while(it!=end())
			{
				it = erase(it);
			}
		}

		~list()
		{
			clear();
			delete _head;
			_head = nullptr;
		}


		void push_back(const T&a)
		{
			/*Node* newnode = new Node(a);
			Node* tail = _head->_prev;

			tail->_next = newnode;
			newnode->_prev = tail;
			newnode->_next = _head;
			_head->_prev = newnode;*/

			insert(end(), a);
		}
		iterator insert(iterator pos, const T& a)
		{
			Node* cur = pos._node;
			Node*prev = cur->_prev;
			Node* next = cur->_next;
			Node *newnode = new Node(a);

			newnode->_prev = prev;
			newnode->_next = cur;
			prev->_next = newnode;
			cur->_prev = newnode;

			return newnode;
		}
		
		iterator erase(iterator pos)
		{
			assert(pos != end());
			Node* tmp = pos._node;
			Node* next = tmp->_next;
			Node* prev = tmp->_prev;


			prev->_next = next;
			next->_prev = prev;
			delete tmp;

			return next;

		}


	private:
		Node* _head;

	};

	void test1()
	{
		list<int> lt;
		lt.push_back(1);
		lt.push_back(2);
		lt.push_back(3);
		lt.push_back(4);
		lt.push_back(5);
		lt.push_back(6);

		list<int> lt2;
		lt2.push_back(1);
		lt2= lt;
		lt.push_back(89);
		list<int>::iterator it = lt2.begin();
		while (it != lt2.end())
		{
			cout << *it << endl;
			++it;
		}
	}

	


}